package com.sl.utils.http;

import com.alibaba.fastjson.JSONObject;
import com.sl.utils.date.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.Map;

/**
 * @author ：zhangC
 * @date ：Created in 2020/9/24 16:09
 * @description：api接口调用
 * @version: $2.0
 */
@Slf4j
@Component
public class NewHttpUtils {
    /**
     * 淘宝时间服务器
     */
    public static final String NET_TIME_URL = "http://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp";

    public static void main(String[] args) {
        Date serverTime = getServerTime();
        log.info("服务器返回时间：{}", serverTime);
    }

    /**
     * 向服务器请求时间
     *
     * @return
     */
    public static Date getServerTime() {
//        log.info("在{}，向服务器请求时间。", new Date());
        JSONObject data = sendGetRequest(NET_TIME_URL, null);
        Date date = null;
        if (null != data) {
            data = (JSONObject) data.get("data");
            Long t = data.getLong("t");
            date = DateUtils.timestampToDate(t);
        }
//        log.info("服务器返回时间：{}", date);
        return date;
    }

    public static RestTemplate restTemplate() {
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        requestFactory.setConnectTimeout(5000);
        requestFactory.setReadTimeout(5000);
        RestTemplate restTemplate = new RestTemplate(requestFactory);
        return restTemplate;
    }

    /**
     * 向目的URL发送post请求
     *
     * @param url    目的url
     * @param params 发送的参数
     * @return AdToutiaoJsonTokenData
     */
    public static JSONObject sendGetRequest(String url, Map<String, Object> params) {
        RestTemplate restTemplate = restTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        //设置请求发送方式
        HttpMethod method = HttpMethod.GET;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
//        headers.add("Authorization","eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDU3Njc2OTYsInVzZXJuYW1lIjoia3ltZDIwMjAifQ.2k0EJPmeeYzMei121K-2KGWnQOWbP1LWzj7jjlkkZ2Y");
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化（可设置为对应返回值格式的类）
        ResponseEntity<String> response;
        try {
            response = restTemplate.exchange(url, method, requestEntity, String.class);
        } catch (RestClientException rce) {
            log.error("get request failed for {}", rce.getMessage());
            return null;
        }
        String responseBody = response.getBody();
        JSONObject json = JSONObject.parseObject(responseBody);
        return json;
    }

    /**
     * 向目的URL发送post请求
     *
     * @param url    目的url
     * @param params 发送的参数
     * @return AdToutiaoJsonTokenData
     */
    public JSONObject sendPostRequest(String url, Map<String, Object> params) {
        RestTemplate restTemplate = restTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        //设置请求发送方式
        HttpMethod method = HttpMethod.POST;
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_JSON);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
//        url = getClient() + url;
        //执行HTTP请求，将返回的结构使用String 类格式化（可设置为对应返回值格式的类）
        ResponseEntity<String> response;
        try {
            response = restTemplate.exchange(url, method, requestEntity, String.class);
        } catch (RestClientException rce) {
            log.error("request failed for {}", rce.getMessage());
            return null;
        }

        String responseBody = response.getBody();
        log.info("返回结果： {}", responseBody);
        JSONObject json = JSONObject.parseObject(responseBody);
        return json;
    }

    /**
     * 向目的URL发送post请求，携带token
     *
     * @param url    目的url
     * @param params 发送的参数
     * @return AdToutiaoJsonTokenData
     */
    public static String sendGetRequest(String url, Map<String, Object> params,String Authorization) {
        RestTemplate restTemplate = restTemplate();
        //新建Http头，add方法可以添加参数
        HttpHeaders headers = new HttpHeaders();
        //设置请求发送方式
        HttpMethod method = HttpMethod.GET;
        // 以表单的方式提交
        headers.add("Authorization",Authorization);
        //将请求头部和参数合成一个请求
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用String 类格式化（可设置为对应返回值格式的类）
        ResponseEntity<String> response;
        try {
            response = restTemplate.exchange(url, method, requestEntity, String.class);
        } catch (RestClientException rce) {
            log.error("get request failed for {}", rce.getMessage());
            return null;
        }
        String responseBody = response.getBody();
        return responseBody;
    }
}
